const socket: WebSocket = new WebSocket("ws://localhost:4600");
let id: NodeJS.Timeout | null = null;
import store from "../stores/MainStore";
import {setUserList,setMessageList} from "../stores/ChatsSlice"
const {user} = store.getState().user;
export default function ChatsInstance() {
    socket.addEventListener("open", opeHandler);
    socket.addEventListener("message", MessageHandler);
    socket.addEventListener("close", closeHandler);
    socket.addEventListener("error", errorHandler);
    return socket;
}

function opeHandler() {
    socket.send(
        JSON.stringify({
            type: 0x01,
            data: {
                userid: user.userid,
                uname: user.uname,
                avatar: user.avatar,
            },
        })
    );
    if (!id) {
        id = setInterval(() => {
            socket.send(
                JSON.stringify({
                    type: 0x07,
                    data: {
                        userid: user.userid,
                    },
                })
            );
        }, 500);
        console.log(id);
    }
}

function MessageHandler(evt: MessageEvent) {
    const result = JSON.parse(evt.data);
    switch (result.type) {
        case 0x02:
           store.dispatch(setUserList(result.data));
            break;
        case 0x04:
           store.dispatch(setMessageList(result.data));
            break;
    }
    console.log(result);
}
function closeHandler(evt: CloseEvent) {
    console.log("close", evt);
}
function errorHandler(evt: Event) {
    closeHandler(evt as CloseEvent);
}

